/*
 * main.c
 *
 *  Created on: 12.05.2011
 *      Author: Thomas Opolka, Axel Seitz, Eugen Schneider
 *     Version: 0.8
 */

#include <avr/interrupt.h>

#include "fixedpoint.h"

#include "sysinit.h"
#include "odometer.h"
#include "gsensor.h"
#include "usiTwiSlave.h"
#include "godos.h"

#define IRT_GSENSOR	10		/* interrupt time gravity sensor */
#define IRT_ODOMETER	500	/* interrupt time odometer */
#define IRT_REVOLUTION	1		/* interrupt time revolution */
#define SLAVE_ADDR_ATTINY       0b00110100	/*address I2C, TWI */

#ifndef 	F_CPU
#define 	F_CPU 16000000UL
#endif

fixedpoint_t g_wOVelocity = 0x0000; /* velocity (gravity sensor) */
fixedpoint_t g_wGVelocity = 0x0000; /* velocity (odometer) */
fixedpoint_t wRevolutionLeft;
fixedpoint_t wRevolutionRight;
fixedpoint_t wAcceleration;
volatile timeSinceStart_t g_dwTime = 0x00000000; /* time (milliseconds) */

volatile uint8_t g_nFlag = 0x00; /* flag */

int main(void) {
	cli();
	/* Disable interrupts */
	uint16_t *buffer = &txbuffer;

	/*initialization*/
	bInitIO();
	bInitODOsensor();
	bInitGsensor();
	bInitADC();
	usiTwiSlaveInit(SLAVE_ADDR_ATTINY); /* TWI slave init */
	bInitTimer();

	sei();
	/*global interrupts enable*/
	while (1) {
		while (g_nFlag == 0)
			; /* check flag */

		g_nFlag = 0; /* unset flag */

		if (!(g_dwTime % IRT_REVOLUTION)) {
			bGetRevolution(&wRevolutionLeft, &wRevolutionRight);
		}
		if (!(g_dwTime % IRT_GSENSOR)) {
					bGetAccelaration(&wAcceleration);
					bGUpdateVelocity(&g_dwTime, &wAcceleration, &g_wGVelocity);
				}
		if (!(g_dwTime % IRT_ODOMETER)) {
			bOUpdateVelocity(&g_dwTime, &wRevolutionLeft, &wRevolutionRight,
					&g_wOVelocity, &g_wGVelocity);
			*buffer = g_wOVelocity;
//			*buffer = 0x3333;
		}

	}

	return 0;
}

ISR(TIMER0_OVF0_vect)
{ /* timer interrupt */
	TCNT0 = 0x06;
	g_dwTime++;
	g_nFlag = 1; /* set flag */
}

